package com.unieagle.exam.ui;

import java.io.File;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.utils.DiskCacheUtils;
import com.nostra13.universalimageloader.utils.MemoryCacheUtils;
import com.unieagle.exam.R;
import com.unieagle.exam.account.AccountManager;
import com.unieagle.exam.camera.CameraActivity;
import com.unieagle.exam.http.BusinessConfig;
import com.unieagle.exam.http.IVolleyListener;
import com.unieagle.exam.http.TaskHelper;
import com.unieagle.exam.http.VolleyRequest;
import com.unieagle.exam.http.VolleyTask;
import com.unieagle.exam.model.UserInfoResult;
import com.unieagle.exam.ui.dialogs.SlideUpMenuDialog;
import com.unieagle.exam.utils.HttpUtils;
import com.unieagle.exam.utils.UriUtils;

/**
 * Created by sun on 2017/6/18.
 */

public class IdentityUploadActivity extends BaseActivity implements IVolleyListener {
    private static final String TAG = "IdentityUploadActivity";
    private static final int CHOSE_IMAGE_FRONT = 7001;
    private static final int CHOSE_IMAGE_BACK = 7002;

    private ImageButton mIbFront;
    private ImageButton mIbBack;
    private int mLastRequestId;
    private ImageButton mBtBack;
    private Button mBtSubmit;

    private String mFrontUri;
    private String mBackUri;
    
    private DisplayImageOptions mIdentityOption;

    private static final String[] Menu = new String[]{"上传身份证","拍照","从手机相册选择"};
    private SlideUpMenuDialog mImageMenuDialog;

    private int sucCount = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        immersedStyle();
        setContentView(R.layout.identity_upload_activity_layout);

        mIbFront = (ImageButton)findViewById(R.id.identity_upload_front);
        mIbBack = (ImageButton)findViewById(R.id.identity_upload_back);
        mBtBack = (ImageButton) findViewById(R.id.back);
        mBtSubmit = (Button)findViewById(R.id.identity_submit);

        mIbFront.setOnClickListener(mOnClickListener);
        mIbBack.setOnClickListener(mOnClickListener);
        mBtBack.setOnClickListener(mOnClickListener);
        mBtSubmit.setOnClickListener(mOnClickListener);

        String front = HttpUtils.getHost() + AccountManager.getInstance().getCertificateFrontUrl();
        String back = HttpUtils.getHost() + AccountManager.getInstance().getCertificateBackUrl();
        if(mIdentityOption == null) {
    		mIdentityOption = new DisplayImageOptions.Builder()
                    .cacheInMemory(true)//设置下载的图片是否缓存在内存中
                    .cacheOnDisk(true)
                    .bitmapConfig(Bitmap.Config.RGB_565)//设置图片的解码类型//
                    .build();//构建完成

        }
        if(!TextUtils.isEmpty(front)){
            ImageLoader.getInstance().displayImage(front, mIbFront, mIdentityOption);
        }
        if(!TextUtils.isEmpty(back)){
            ImageLoader.getInstance().displayImage(back, mIbBack, mIdentityOption);
        }
    }

    View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int id = view.getId();
            switch (id){
                case R.id.identity_upload_front:
                    uploadMenu(CHOSE_IMAGE_FRONT);
                    break;
                case R.id.identity_upload_back:
                    uploadMenu(CHOSE_IMAGE_BACK);
                    break;
                case R.id.back:
                    finish();
                    break;
                case R.id.identity_submit:
                    if(mFrontUri == null){
                        Toast.makeText(IdentityUploadActivity.this, "还未指定正面", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if(mBackUri == null){
                        Toast.makeText(IdentityUploadActivity.this, "还未指定背面", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if(loginCheck()) {
                        asyncUpload(mFrontUri, BusinessConfig.UPLOAD_IMAGE_TYPE_FRONT,CHOSE_IMAGE_FRONT);
                        asyncUpload(mBackUri, BusinessConfig.UPLOAD_IMAGE_TYPE_BACK, CHOSE_IMAGE_BACK);
                        sucCount = 0;
                    }
                    break;
            }
        }
    };

    private void uploadMenu(int id){
        mLastRequestId = id;
        if(mImageMenuDialog == null) {
            mImageMenuDialog = new SlideUpMenuDialog(this);
            mImageMenuDialog.setOnItemClickListener(new ListView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    choseImage(i,mLastRequestId);
                }
            });
            if (Build.VERSION.SDK_INT >= 21) {
                mImageMenuDialog.create();
            }
        }
        mImageMenuDialog.show(1, Menu);
    }

    public void choseImage(int type,int id){
        switch (type){
            case 1:
                startActivityForResult(new Intent(this, CameraActivity.class),id);
                break;
            case 2:
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("image/*");
                startActivityForResult(Intent.createChooser(intent, "选择图片"), id);
                break;
        }
    }

    private void asyncUpload(String uri, String type,int id){
        String path = UriUtils.getPath(this, uri);
        if(TextUtils.isEmpty(path)){
            return ;
        }
        VolleyTask task;
        File file = new File(path);
        if (file.exists()) {
            task = TaskHelper.createUploadImageTask(type, file);
            task.setVolleyListener(IdentityUploadActivity.this);
            task.setId(id);
            VolleyRequest.getInstance().request(task);
            showProgress("上传中");
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == CHOSE_IMAGE_FRONT){
            if(data != null) {
                ImageLoader.getInstance().displayImage(data.getData().toString(), mIbFront);
                mFrontUri = data.getData().toString();
            }
        }else if(requestCode == CHOSE_IMAGE_BACK){
            if(data != null) {
                ImageLoader.getInstance().displayImage(data.getData().toString(), mIbBack);
                mBackUri = data.getData().toString();
            }
        }
    }

    @Override
    public void onComplete(VolleyTask task, Object result) {
        if(result instanceof UserInfoResult){
            AccountManager.getInstance().updateUserInfoResult((UserInfoResult)result);
        }
        sucCount++;
        if(sucCount >= 2){
        	String front = HttpUtils.getHost() + AccountManager.getInstance().getCertificateFrontUrl();
            String back = HttpUtils.getHost() + AccountManager.getInstance().getCertificateBackUrl();
        	DiskCacheUtils.removeFromCache(front, ImageLoader.getInstance().getDiskCache());    
            MemoryCacheUtils.removeFromCache(front, ImageLoader.getInstance().getMemoryCache());
            DiskCacheUtils.removeFromCache(back, ImageLoader.getInstance().getDiskCache());    
            MemoryCacheUtils.removeFromCache(back, ImageLoader.getInstance().getMemoryCache());
            Toast.makeText(this, "上传成功", Toast.LENGTH_SHORT).show();
            dismissProgress();
            setResult(RESULT_OK);
            finish();
        }
    }

    @Override
    public void onError(VolleyTask task, VolleyError volleyError) {
        if(task.getId() == CHOSE_IMAGE_FRONT){
            Toast.makeText(this, "上传正面失败", Toast.LENGTH_SHORT).show();
        }else if(task.getId() == CHOSE_IMAGE_BACK){
            Toast.makeText(this, "上传背面失败", Toast.LENGTH_SHORT).show();
        }
        dismissProgress();
    }
}
